<template>
  <div class="app-layout">
    <aside class="sidebar">
      <div class="logo-section">
        <img src="@/assets/logo.jpg" alt="智能养殖管理系统" class="logo-img" />
        <span class="logo-text">智能养殖管理系统</span>
      </div>
      <div class="user-info">
        <div class="user-avatar">
          <i class="fa-solid fa-user"></i>
        </div>
        <span class="username">{{ userInfo.nickName || userInfo.username || '用户' }}</span>
      </div>
      <el-button class="new-chat-button" @click="newChat">
        <i class="fa-solid fa-plus"></i>
        &nbsp;新会话
      </el-button>
      <el-button class="logout-button" @click="handleLogout" type="danger">
        <i class="fa-solid fa-sign-out-alt"></i>
        &nbsp;退出登录
      </el-button>
    </aside>
    <main class="main-content">
      <section class="chat-container">
        <div class="message-list" ref="messaggListRef">
          <div
            v-for="(message, index) in messages"
            :key="index"
            :class="message.isUser ? 'message user-message' : 'message bot-message'"
          >
            <i
              :class="message.isUser ? 'fa-solid fa-user message-icon user' : 'fa-solid fa-robot message-icon bot'"
            ></i>
            <span class="message-content">
              <span v-html="message.content"></span>
              <span class="loading-dots" v-if="message.isThinking || message.isTyping">
                <span class="dot"></span>
                <span class="dot"></span>
              </span>
            </span>
          </div>
        </div>
        <div class="input-container">
          <el-input
            v-model="inputMessage"
            placeholder="请输入养殖管理相关问题或指令"
            @keyup.enter="sendMessage"
          ></el-input>
          <el-button @click="sendMessage" :disabled="isSending" type="primary" class="send-btn">
            <i class="fa-solid fa-paper-plane"></i>&nbsp;发送
          </el-button>
        </div>
      </section>
    </main>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import axios from 'axios'
import { v4 as uuidv4 } from 'uuid'
import logo from "@/assets/logo.jpg"
import request from '@/utils/request'

const emit = defineEmits(['logout'])

const messaggListRef = ref()
const isSending = ref(false)
const uuid = ref()
const inputMessage = ref('')
const messages = ref([])
const userInfo = ref({})

const fetchUserInfo = async () => {
  try {
    const res = await request.get('/user/getUserInfo')
    if (res.data.code === 200) {
      userInfo.value = res.data.data
      localStorage.setItem('userInfo', JSON.stringify(res.data.data))
    }
  } catch (e) {
    // 处理异常
  }
}

onMounted(() => {
  initUUID()
  fetchUserInfo()
  watch(messages, () => scrollToBottom(), { deep: true })
  hello()
})

const scrollToBottom = () => {
  if (messaggListRef.value) {
    messaggListRef.value.scrollTop = messaggListRef.value.scrollHeight
  }
}

const hello = () => {
  sendRequest('你好，欢迎使用智能养殖管理系统！')
}

const sendMessage = () => {
  if (inputMessage.value.trim()) {
    sendRequest(inputMessage.value.trim())
    inputMessage.value = ''
  }
}

const sendRequest = (message) => {
  isSending.value = true
  const userMsg = {
    isUser: true,
    content: message,
    isTyping: false,
    isThinking: false,
  }
  if(messages.value.length > 0){
    messages.value.push(userMsg)
  }
  const botMsg = {
    isUser: false,
    content: '',
    isTyping: true,
    isThinking: false,
  }
  messages.value.push(botMsg)
  const lastMsg = messages.value[messages.value.length - 1]
  scrollToBottom()
  axios
    .post(
      '/farming/chat',
      { memoryId: uuid.value, message },
      {
        responseType: 'stream',
        onDownloadProgress: (e) => {
          const fullText = e.event.target.responseText
          let newText = fullText.substring(lastMsg.content.length)
          lastMsg.content += newText
          scrollToBottom()
        },
      }
    )
    .then(() => {
      messages.value.at(-1).isTyping = false
      isSending.value = false
    })
    .catch((error) => {
      messages.value.at(-1).content = '请求失败，请重试'
      messages.value.at(-1).isTyping = false
      isSending.value = false
    })
}

const initUUID = () => {
  let storedUUID = localStorage.getItem('user_uuid')
  if (!storedUUID) {
    storedUUID = uuidToNumber(uuidv4())
    localStorage.setItem('user_uuid', storedUUID)
  }
  uuid.value = storedUUID
}

const uuidToNumber = (uuid) => {
  let number = 0
  for (let i = 0; i < uuid.length && i < 6; i++) {
    const hexValue = uuid[i]
    number = number * 16 + (parseInt(hexValue, 16) || 0)
  }
  return number % 1000000
}

const handleLogout = () => {
  emit('logout')
}

const newChat = () => {
  localStorage.removeItem('user_uuid')
  messages.value = []
  hello()
}
</script>

<style scoped>
.app-layout {
  display: flex;
  height: 100vh;
  background: linear-gradient(135deg, #e0eafc 0%, #cfdef3 100%);
}

.sidebar {
  width: 270px;
  background: linear-gradient(180deg, #43cea2 0%, #185a9d 100%);
  padding: 32px 20px 20px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 2px 0 16px rgba(0, 0, 0, 0.08);
  border-top-right-radius: 32px;
  border-bottom-right-radius: 32px;
}

.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 32px;
}
.logo-img {
  width: 90px;
  height: 90px;
  border-radius: 50%;
  box-shadow: 0 4px 16px rgba(67, 206, 162, 0.2);
  margin-bottom: 12px;
}
.logo-text {
  font-size: 22px;
  font-weight: 700;
  color: #fff;
  letter-spacing: 2px;
  text-shadow: 0 2px 8px rgba(24, 90, 157, 0.15);
}
.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 18px 0 24px 0;
  padding: 12px 18px;
  background: rgba(255,255,255,0.85);
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(67, 206, 162, 0.08);
}
.user-avatar {
  width: 38px;
  height: 38px;
  background: linear-gradient(135deg, #43cea2 0%, #185a9d 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 18px;
  box-shadow: 0 2px 8px rgba(24, 90, 157, 0.08);
}
.username {
  font-weight: 600;
  color: #185a9d;
  font-size: 15px;
}
.new-chat-button, .logout-button {
  width: 100%;
  margin-top: 12px;
  border-radius: 12px;
  font-weight: 600;
  font-size: 16px;
  box-shadow: 0 2px 8px rgba(67, 206, 162, 0.08);
  transition: all 0.2s;
}
.new-chat-button {
  background: linear-gradient(90deg, #43cea2 0%, #185a9d 100%);
  color: #fff;
  border: none;
}
.new-chat-button:hover {
  background: #43cea2;
  color: #fff;
  transform: translateY(-2px) scale(1.03);
}
.logout-button {
  background: linear-gradient(90deg, #ff5858 0%, #f09819 100%);
  color: #fff;
  border: none;
}
.logout-button:hover {
  background: #ff5858;
  color: #fff;
  transform: translateY(-2px) scale(1.03);
}
.main-content {
  flex: 1;
  padding: 0;
  display: flex;
  flex-direction: column;
  background: rgba(255,255,255,0.95);
  border-top-left-radius: 32px;
  border-bottom-left-radius: 32px;
  box-shadow: -2px 0 16px rgba(24, 90, 157, 0.06);
}
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 32px 24px 24px 24px;
}
.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 18px 0 18px 0;
  border-radius: 18px;
  background: rgba(255,255,255,0.7);
  margin-bottom: 18px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4px 24px rgba(67, 206, 162, 0.06);
}
.message {
  margin-bottom: 18px;
  padding: 16px 20px;
  border-radius: 16px;
  display: flex;
  align-items: flex-start;
  animation: messageSlide 0.3s ease-out;
  box-shadow: 0 2px 8px rgba(24, 90, 157, 0.04);
}
@keyframes messageSlide {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
.user-message {
  max-width: 70%;
  background: linear-gradient(135deg, #43cea2 0%, #185a9d 100%);
  color: #fff;
  align-self: flex-end;
  flex-direction: row-reverse;
  box-shadow: 0 4px 15px rgba(67, 206, 162, 0.13);
}
.bot-message {
  max-width: 100%;
  background: rgba(255,255,255,0.95);
  color: #185a9d;
  align-self: flex-start;
  box-shadow: 0 4px 15px rgba(24, 90, 157, 0.08);
  border: 1px solid rgba(67, 206, 162, 0.08);
}
.message-icon {
  margin: 0 14px 0 0;
  font-size: 1.4em;
  opacity: 0.85;
}
.message-icon.user {
  color: #43cea2;
}
.message-icon.bot {
  color: #185a9d;
}
.message-content {
  flex: 1;
  word-break: break-all;
  font-size: 16px;
  line-height: 1.7;
}
.loading-dots {
  padding-left: 8px;
}
.dot {
  display: inline-block;
  margin-left: 5px;
  width: 8px;
  height: 8px;
  background-color: #43cea2;
  border-radius: 50%;
  animation: pulse 1.2s infinite ease-in-out both;
}
.dot:nth-child(2) {
  animation-delay: -0.6s;
}
@keyframes pulse {
  0%, 100% { transform: scale(0.6); opacity: 0.4; }
  50% { transform: scale(1); opacity: 1; }
}
.input-container {
  display: flex;
  gap: 16px;
  padding: 0;
  background: none;
  border-radius: 0;
  box-shadow: none;
}
.input-container .el-input {
  flex: 1;
}
.input-container .el-input :deep(.el-input__wrapper) {
  border-radius: 12px;
  border: 2px solid #43cea2;
  background: #f7fafc;
  transition: all 0.3s ease;
}
.input-container .el-input :deep(.el-input__wrapper:hover) {
  border-color: #185a9d;
}
.input-container .el-input :deep(.el-input__wrapper.is-focus) {
  border-color: #185a9d;
  box-shadow: 0 0 0 3px rgba(67, 206, 162, 0.12);
}
.send-btn {
  border-radius: 12px;
  background: linear-gradient(90deg, #43cea2 0%, #185a9d 100%);
  color: #fff;
  font-weight: 700;
  font-size: 16px;
  border: none;
  padding: 0 24px;
  transition: all 0.2s;
  box-shadow: 0 2px 8px rgba(67, 206, 162, 0.08);
}
.send-btn:hover {
  background: #43cea2;
  color: #fff;
  transform: translateY(-2px) scale(1.03);
}
@media (max-width: 900px) {
  .sidebar {
    width: 100%;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 12px 8px;
    border-radius: 0 0 24px 24px;
  }
  .main-content {
    border-radius: 24px 24px 0 0;
  }
  .chat-container {
    padding: 16px 6px 6px 6px;
  }
}
@media (max-width: 600px) {
  .app-layout {
    flex-direction: column;
  }
  .sidebar {
    width: 100%;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 10px 4px;
    border-radius: 0 0 18px 18px;
  }
  .main-content {
    border-radius: 18px 18px 0 0;
  }
  .chat-container {
    padding: 8px 2px 2px 2px;
  }
  .logo-img {
    width: 48px;
    height: 48px;
  }
  .logo-text {
    font-size: 15px;
  }
  .user-info {
    padding: 6px 8px;
    font-size: 12px;
  }
  .user-avatar {
    width: 24px;
    height: 24px;
    font-size: 12px;
  }
  .username {
    font-size: 12px;
  }
  .new-chat-button, .logout-button, .send-btn {
    font-size: 13px;
    padding: 0 10px;
  }
  .message {
    font-size: 13px;
    padding: 8px 10px;
    border-radius: 10px;
  }
  .message-content {
    font-size: 13px;
  }
}
</style>
